<template>
  <el-dialog :title="titleText" :visible.sync="showDialog" top="0" :close-on-click-modal="false" @close="cancel">
    <div class="dia-wrapper">
      <el-form ref="form" label-position="left" label-width="50px" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="批次名称：" prop="batchName" class="w100p">
          <el-input v-model="formData.batchName" placeholder="请输入批次名称" clearable />
        </el-form-item>
        <el-form-item label="批次号：" prop="batchNo" class="w100p">
          <el-input v-model="formData.batchNo" disabled placeholder="请输入产线名称" clearable />
        </el-form-item>
        <el-form-item label="加工产品：" prop="productId" class="w100p">
          <el-select v-model="formData.productId" filterable clearable placeholder="请选择加工产品" @change="changeProd">
            <el-option v-for="item in productList" :key="item.productId" :label="item.productName" :value="item.productId" />
          </el-select>
        </el-form-item>
        <el-form-item label="预估批次加工总量：" prop="processingVolume" class="w100p">
          <div class="input-group">
            <el-input v-model="formData.processingVolume" placeholder="预估批次加工总量" clearable @input="changeProcessingVolume" />
            <el-input :value="prodUnitName" placeholder="单位" disabled clearable />
          </div>
        </el-form-item>
        <el-form-item label="加工开始时间：" prop="startTime" class="w100p">
          <el-date-picker v-model="formData.startTime" type="date" placeholder="请选择加工开始时间" />
        </el-form-item>
        <el-form-item label="加工结束时间：" prop="endTime" class="w100p">
          <el-date-picker v-model="formData.endTime" type="date" placeholder="请选择加工结束时间" />
        </el-form-item>
        <el-form-item label="加工类型" prop="batchType">
          <el-radio-group v-model="formData.batchType" style="flex:0 0 55%;" @change="batchTypeChange">
            <el-radio label="SELF">自主生产</el-radio>
            <el-radio label="COMMISSION">委托加工</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.batchType === 'COMMISSION'" label="委托加工商" prop="manufacturingId" class="w100p">
          <el-select v-model="formData.manufacturingId" style="flex:1;" filterable clearable placeholder="请选择委托加工商">
            <el-option v-for="item in manufacturingList" :key="item.manufacturingId" :label="item.manufacturingName" :value="item.manufacturingId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="materialList.length !== 0" class="material-list">
        <div v-for="(item, index) in materialList" :key="index" class="list-item">
          <span>加工原料：{{ item.materialName }}</span>
          <span>预计领料数量：{{ item.expectNum }} {{ item.material.unitName }}</span>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
      <el-button :loading="saveLoading" type="primary" class="savebtn" @click="save()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/api/processing-management/process-batch-manage/process-batch-creation/index';
import ProcessBatchApi from '@/api/processing-management/process-batch-manage/process-batch-creation/index';
import entrustedApi from '@/api/processing-management/basic-info-manage/entrusted-processing-unit-manage/index';
export default {
  components: {},
  props: {
    value: Boolean,
    selectedItem: {
      type: Object,
      default: null
    },
    productList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      formDataDefault: {
        batchName: '',
        batchNo: '',
        productId: '',
        processingVolume: '',
        startTime: '',
        endTime: '',
        batchType: 'SELF',
        manufacturingId: ''
      },
      formData: {},
      saveLoading: false,
      showDialog: false,
      rules: {
        batchName: [
          {
            required: true,
            message: '请选择批次名称'
          }
        ],
        batchNo: [
          {
            required: true,
            message: '请填写批次号'
          }
        ],
        productId: [
          {
            required: true,
            message: '请选择加工产品'
          }
        ],
        processingVolume: [
          {
            required: true,
            message: '请填写预估批次加工总量',
            trigger: 'manual'
          }
        ],
        startTime: [
          {
            required: true,
            message: '请选择加工开始时间'
          }
        ],
        endTime: [
          {
            required: true,
            message: '请选择加工结束时间'
          }
        ],
        batchType: [
          {
            required: true,
            message: '请选择加工类型'
          }
        ],
        manufacturingId: [
          {
            required: false,
            message: '请选择委托加工商'
          }
        ]
      },
      processBatchNo: '',
      manufacturingList: [],
      prodUnitName: '',
      materialList: []
    };
  },
  computed: {
    titleText() {
      return this.selectedItem ? '编辑批次' : '新增批次';
    }
  },
  watch: {
    value(v) {
      this.showDialog = v;
      if (v) {
        this.init();
      }
    }
  },
  created() {
    this.reset();
    this.changeProcessingVolume = this.debounce(this.changeProcessingVolume, 300);
  },
  mounted() {},
  methods: {
    reset() {
      this.formData = JSON.parse(JSON.stringify(this.formDataDefault));
      this.prodUnitName = '';
      this.materialList = [];
    },
    init() {
      const { selectedItem, formData } = this;
      if (selectedItem) {
        for (const key in formData) {
          if (Object.hasOwnProperty.call(formData, key)) {
            formData[key] = selectedItem[key];
          }
        }
        this.changeProd(selectedItem.productId);
      }
      this.getInputStorageNo();
      this.getManufacturing();
    },
    save() {
      const { formData, selectedItem } = this;
      const paylod = JSON.parse(JSON.stringify(formData));
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.saveLoading = true;
          paylod.startTime = this.$moment(paylod.startTime).format('YYYY-MM-DD HH:mm:ss');
          paylod.endTime = this.$moment(paylod.endTime).format('YYYY-MM-DD HH:mm:ss');
          if (selectedItem) {
            paylod.batchId = selectedItem.batchId;
            api
              .edit(paylod)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoading = false;
              });
          } else {
            api
              .add(paylod)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoading = false;
              });
          }
        }
      });
    },
    close() {
      setTimeout(() => {
        this.reset();
        this.$refs['form'].resetFields();
      }, 250);
      this.$emit('input', false);
    },
    cancel() {
      setTimeout(() => {
        this.reset();
        this.$refs['form'].resetFields();
      }, 250);
      this.$emit('input', false);
    },
    getInputStorageNo() {
      ProcessBatchApi.generateNo().then(res => {
        if (res.code === 1) {
          this.processBatchNo = res.data;
          this.formData.batchNo = res.data;
        }
      });
    },
    getManufacturing() {
      entrustedApi.queryByConditionList({}).then(res => {
        if (res.code === 1) {
          this.manufacturingList = res.data;
        }
      });
    },
    queryBomByProduct() {
      const { processingVolume, productId } = this.formData;
      if (processingVolume && productId) {
        api.queryBomByProduct(processingVolume, productId).then(res => {
          if (res.code === 1) {
            this.materialList = res.data;
          }
        });
      }
    },
    batchTypeChange(v) {
      if (v === 'COMMISSION') {
        this.rules.manufacturingId[0].required = true;
      }
    },
    changeProd(v) {
      const findProduct = this.productList.find(item => item.productId === v);
      this.prodUnitName = findProduct.material.unitName;
      this.queryBomByProduct();
    },
    changeProcessingVolume(v) {
      this.queryBomByProduct();
    },
    debounce(fn, delay) {
      let timer = null;
      return function() {
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, arguments);
        }, delay);
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.input-group {
  display: flex;
  align-items: center;
  width: 100%;
  > * {
    &:first-of-type {
      flex: 0 0 70%;
    }
  }
}
::v-deep .el-form-item {
  width: 100%;
  align-items: center !important;
}
.material-list {
  margin-top: 24px;
  padding: 24px 47px;
  box-sizing: border-box;
  background: #e9f8fd;
  border-radius: 10px;
  border: 1px solid #c9e0e7;
  .list-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    span {
      flex: 1;
    }
    &:last-of-type {
      margin-bottom: 0;
    }
  }
}
</style>
